package com.mybatisplugin.springboot.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.mybatisplugin.springboot.Application;
import com.mybatisplugin.springboot.util.CodeResult;
import com.mybatisplugin.springboot.util.GsonUtil;

public class ExceptionHandler implements HandlerExceptionResolver{

	private static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception e) {		
		String errorMsg = e.getMessage();
		if(e instanceof UnauthorizedException){
			errorMsg = "权限不足";
 	   	}else{
	 	   	logger.error("全局异常捕获", e);
			e.printStackTrace();
 	   	}
		
		ModelAndView mv = new ModelAndView();
		// 判断是否 Ajax 请求 
        if ((request.getHeader("accept").indexOf("application/json") > -1 ||
        		(request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))){             
			try {
				response.setContentType("text/html;charset=UTF-8");
	            response.setCharacterEncoding("UTF-8");
	            PrintWriter writer;
				writer = response.getWriter();
				CodeResult cr = new CodeResult(false,errorMsg,"-1");
				writer.write(GsonUtil.toJson(cr));
				writer.write("");
	            writer.flush();
	            writer.close();
			} catch (IOException ex) {
				ex.printStackTrace();
				logger.error("全局异常捕获", ex);
			}
           return null;
       }else{ 	   
			HttpSession sesssion = request.getSession();
			mv.addObject("errorMsg", errorMsg);
			mv.setViewName("error");
       }	
		return mv;
		
	}

}
